package com.yimi.yinhepda.base;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.device.ScanManager;
import android.device.scanner.configuration.PropertyID;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.widget.Toast;

import com.baidu.mobstat.StatService;
import com.scandecode.ScanDecode;
import com.scandecode.inf.ScanInterface;
import com.yimi.yinhepda.R;
import com.yimi.yinhepda.utils.ActivityStack2;
import com.pda.ym.utils.Constants;
import com.pda.ym.utils.FastClick;
import com.pda.uce.commom.util.MyDialog;
import com.pda.ym.utils.PhoneInfoForSimPhone;
import com.pda.ym.utils.ScannerHelper;
import com.pda.ym.utils.SharedPreferUtil;
import com.pda.ym.utils.SoundVibratorManager;
import com.zltd.sdk.scanner.compat.IScanResult;
import com.zltd.sdk.scanner.compat.adapter.ScanAdapter;

import java.util.List;

/**
 * @author 000432
 */

public abstract class BaseActivity2<V extends BaseContract.BaseView, H extends BaseContract.BaseBiz, T extends BasePresenter<V, H>>
        extends AppCompatActivity implements BaseContract.BaseView {

    /**
     * Presenter 泛型变量
     */
    protected T mT;
    protected MyDialog mPgDlg;
    protected boolean isScan = false;
    protected SharedPreferUtil sharedPreferUtil = SharedPreferUtil.getInstance();
    /**
     * SPEEDATA设备扫描接口
     */
    private ScanInterface scanInterface;

    /**
     * 扫码值
     */
    protected static String barCode;
    /**
     * 智联，适配器
     */
    protected ScanAdapter mScanAdapter = ScanAdapter.getInstance();
    /**
     * 智联，扫码监听
     */
    private IScanResult mIScanResult = new IScanResult() {
        @Override
        public void onScanSuccess(String code) {
            barCode = code;
            getBarCode(barCode);
        }

        @Override
        public void onScanError(String msg) {
            getBarCode(null);
        }
    };

    public BaseActivity2() {
        isScan = false;
    }

    public BaseActivity2(boolean isScan) {
        this.isScan = isScan;
    }

    protected BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (!isEnable) {
                return;
            }
            if (action.equals(Constants.BARCODE_ACTION)) {
                barCode = intent.getStringExtra(Constants.BARCODE_VALUE);
                getBarCode(barCode);
            } else if (action.equals(SCAN_ACTION)) {
                byte[] barcode = intent.getByteArrayExtra(ScanManager.DECODE_DATA_TAG);
                int barcodelen = intent.getIntExtra(ScanManager.BARCODE_LENGTH_TAG, 0);
                barCode = new String(barcode, 0, barcodelen);
                getBarCode(barCode);
            }
        }
    };

    protected void handleBarCode(String result) {

    }

    private void getBarCode(String result) {
        if (MyDialog.getTag() == 1) {
            //弹时间校验框，不返回扫描结果
            return;
        }
        handleBarCode(result);
    }

    public SharedPreferUtil getSharedPreferUtil() {
        return sharedPreferUtil;
    }

    /**
     * 注册广播
     */
    protected void registReceiver() {
        //优博讯扫描初始化
        initScan();
        IntentFilter filter = new IntentFilter(Constants.BARCODE_ACTION);
        //优博讯注册广播
        if (mScanManager != null) {
            int[] idbuf = new int[]{PropertyID.WEDGE_INTENT_ACTION_NAME, PropertyID.WEDGE_INTENT_DATA_STRING_TAG};
            String[] valueBuf = mScanManager.getParameterString(idbuf);
            if (valueBuf != null && valueBuf[0] != null && !"".equals(valueBuf[0])) {
                SCAN_ACTION = valueBuf[0];
                filter.addAction(SCAN_ACTION);
            } else {
                filter.addAction(SCAN_ACTION);
            }
        }

        registerReceiver(mBroadcastReceiver, filter);
    }

    /**
     * 解注册广播
     */
    protected void unRegistReceiver() {
        //优博讯关闭扫描
        if (mScanManager != null) {
            mScanManager.stopDecode();
            mScanManager.closeScanner();
            mScanManager = null;
        }

        Intent intent = new Intent();
        intent.setAction(Constants.BARCODE_ACTION);
        PackageManager pm = getPackageManager();
        List<ResolveInfo> resolveInfos = pm.queryBroadcastReceivers(intent, 0);
        //判断广播是否已注册
        if (resolveInfos != null && !resolveInfos.isEmpty()) {
            //查询到相应的BroadcastReceiver
            if (mBroadcastReceiver != null) {
                unregisterReceiver(mBroadcastReceiver);
            }
        }
    }

    /**
     * 是否能扫描，主要是为了不使东大的机器，控制不扫描
     */
    boolean isEnable = false;

    public void setScannerEnabled(boolean enable) {
        isEnable = enable;
        ScannerHelper.sendBroadcast(this, ScannerHelper.ACTION_SCANNER_ENABLED, ScannerHelper.KEY_ENABLED, enable);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyDialog.setNull();
        ActivityStack2.getInstance().addActivity(this);
        mT = createPresenter();
        mT.onAttach((V) this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        FastClick.lastClickTime = 0;

        StatService.onPageStart(this, getPageName());

        SoundVibratorManager.initSounds(BaseApplication.getContext());
        SoundVibratorManager.addSound(1, R.raw.scan_success);
        SoundVibratorManager.addSound(2, R.raw.scan_failed);
        //智联，初始化设备信息
        PhoneInfoForSimPhone.setOs();

        if (isScan) {
            enableScan();
        }
    }

    /**
     * 提供页面统计名称的方法, 由子类实现
     */
    public String getPageName() {
        return "基础页面";
    }

    @Override
    protected void onPause() {
        super.onPause();
        StatService.onPageEnd(this, getPageName());

        SoundVibratorManager.cleanup();

        if (isScan) {
            disableScan();
            unRegistReceiver();
        }
    }

    public void enableScan() {
        //注册广播监听
        registReceiver();
        //启用扫描
        setScannerEnabled(true);
        //智联，如果是智联的，初始化扫描
        if (PhoneInfoForSimPhone.isAdapted()) {
            mScanAdapter.openBySingleModel(this, mIScanResult);
        }

        try {
            //工业手机初始化扫描服务
            scanInterface = new ScanDecode(this);
            scanInterface.initService("true");
            scanInterface.getBarCode(new ScanInterface.OnScanListener() {
                @Override
                public void getBarcode(String data) {
                    getBarCode(data);
                }
            });
        } catch (Exception e) {
            scanInterface = null;
        }
    }

    public void disableScan() {
        unRegistReceiver();
        //禁用扫描
        setScannerEnabled(false);
        //智联，禁用扫描
        mScanAdapter.removeScanResult();
        //工业手机初始化扫描服务
        if (scanInterface != null) {
            scanInterface.initService("true");
            scanInterface.onDestroy();
            scanInterface.stopScan();
        }
    }

    /**
     * 创建一个指定的Presenter
     *
     * @return 指定的Presenter t
     */
    public abstract T createPresenter();

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    public String getTAG() {
        return getContext().getClass().getName();
    }

    public void showPgDlg(String msg) {
        if (mPgDlg == null) {
            mPgDlg = new MyDialog(this);
            mPgDlg.setCancelable(false);
            mPgDlg.setCanceledOnTouchOutside(false);
            mPgDlg.setDialogType(MyDialog.DialogType.PROGRESS_DIALOG);
        }
        mPgDlg.setMessage(msg);
        if (!mPgDlg.isShowing()) {
            mPgDlg.show();
        }
    }

    protected void showPgDlg(String msg, boolean cancelable) {
        if (mPgDlg == null) {
            mPgDlg = new MyDialog(this);
            mPgDlg.setCancelable(cancelable);
            mPgDlg.setCanceledOnTouchOutside(false);
            mPgDlg.setDialogType(MyDialog.DialogType.PROGRESS_DIALOG);
        }
        mPgDlg.setMessage(msg);
        mPgDlg.show();
    }

    public void dismissPgDlg() {
        try {
            if (mPgDlg != null) {
                mPgDlg.dismiss();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void toActivity(Class mClass) {
        Intent intent = new Intent(this, mClass);
        startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mT.onDetach();
        ActivityStack2.getInstance().deleteActivity(this);
    }

    public void showToast(String content) {
        Toast.makeText(this, content, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    /**************************************优博讯**************************************/
    private String SCAN_ACTION = ScanManager.ACTION_DECODE;
    private ScanManager mScanManager;

    private void initScan() {
        try {
            mScanManager = new ScanManager();
            mScanManager.openScanner();

            mScanManager.switchOutputMode(0);
        } catch (Exception e) {
            e.printStackTrace();
            mScanManager = null;
        }
    }

    /**
     * 智联，扫描按键监听
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (PhoneInfoForSimPhone.isAdapted() && mScanAdapter.onKeyDown(keyCode, event)) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 智联，扫描按键监听
     */
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (PhoneInfoForSimPhone.isAdapted() && mScanAdapter.onKeyUp(keyCode, event)) {
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    /**
     * 智联，扫描按键监听
     */
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {

        if (PhoneInfoForSimPhone.isAdapted() && mScanAdapter.dispatchKeyEvent(event)) {
            return true;
        }
        return super.dispatchKeyEvent(event);
    }
}
